package com.partners.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.partners.configure.wechatmp.WxMpConfiguration;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.dto.TaskInputDTO;
import com.partners.dao.basic.*;
import com.partners.dao.bo.TaskDO;
import com.partners.dao.bo.TaskReadDO;
import com.partners.dao.bo.UserTaskDO;
import com.partners.dao.bo.WxTemplateDO;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.TaskService;
import com.partners.utils.JsonUtils;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangyongle
 * @date 2018-12-24
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Resource
    private TaskDao taskDao;

    @Resource
    private UserTaskDao userTaskDao;

    @Resource
    private TaskReadDao taskReadDao;

    @Resource
    private UserDao userDao;

    @Resource
    private WxTemplateDao wxTemplateDao;

    @Resource
    private WxMpProperties wxMpProperties;


    /**
     * 获取我的任务列表
     * @param uid  Integer
     * return list
     * */
    @Override
    public Map<String, Object> getMyTaskList(Paging paging, Integer uid) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String,Object>> list = taskDao.getMyTaskList(uid);
        Page page = (Page) list;
        Object total = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }


    /**
     * 获取所有的任务列表
     * @param paging Paging
     *        title String
     *        classId Integer
     * return list
     * */
    @Override
    public Map<String, Object> getAllTaskList(Paging paging,
                                              Integer classId,
                                              String title,
                                              Integer timeType,
                                              Integer returnType) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        if(title != null){
            title = "%"+title+"%";
        }
        Integer nowTime = TimestampUtils.timestamp();
        List<Map<String,Object>> list = taskDao.getAllTaskList(classId,title,timeType,nowTime);
        Page page = (Page) list;
        Object total = page.getTotal();
        allList.put("total",total);
        if(returnType == 1){
            Map<Object, List<Map<String, Object>>> timeList = JsonUtils.toMonthList(list);
            allList.put("list",timeList);
        }else{
            allList.put("list",list);
        }
        for (Map<String,Object> map:list){
            String timeFormat = "yyyy-MM-dd";
            String addFormat = "dd/MM";
            String ddFormat = "dd";
            String mmFormat = "MM";
            String start_time = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("start_time"),timeFormat);
            String end_time = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("end_time"),timeFormat);
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),addFormat);
            String dd = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),ddFormat);
            String mm = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),mmFormat);
            map.put("start_time",start_time);
            map.put("end_time",end_time);
            map.put("addtime",addtime);
            map.put("mm",mm);
            map.put("dd",dd);
        }
        return allList;
    }


    /**
     * 发布任务
     * @param taskInputDTO TaskInputDTO
     * return boolean
     * */
    @Override
    @Transactional
    public void publishTask(TaskInputDTO taskInputDTO) {
        //1.查询当前的任务是否存在
        //2.任务是否已过期
        //3.发送任务
        //4.发送模板消息通知
        TaskDO taskDO = taskDao.selectByPrimaryKey(taskInputDTO.getId());
        if(taskDO == null){
            //不存在
            throw BusinessException.of(ErrorMessageEnum.TASK_NOT_FOUND);
        }
        Integer nowTime = TimestampUtils.timestamp();
        if(nowTime >taskDO.getEndTime()){
            //已过期
            throw  BusinessException.of(ErrorMessageEnum.TASK_IS_OVERTIME);
        }
        //分配任务
        UserTaskDO userTaskDO = new UserTaskDO();
        for (Integer i:taskInputDTO.getUserlist()){
            userTaskDO.setTaskId(taskInputDTO.getId());
            userTaskDO.setUid(i);
            userTaskDO.setAddtime(TimestampUtils.timestamp());
            userTaskDao.insertSelective(userTaskDO);
        }
        //写入批量发送表
        List<String> userOpenId = userDao.selectOpenidByUserId(taskInputDTO.getUserlist());
        WxTemplateDO wxTemplateDO = new WxTemplateDO();
        String first = "任务推送通知";
        String keyword1 = "您收到一条新的任务，快进去看看";
        String keyword2 = TimestampUtils.getSimpleDateFormat("yyyy-MM-dd");
        //String url = "baidu.com";
        String baseUrl = wxMpProperties.getBaseUrl();
        String url = baseUrl+"/taskPage/takInfo?id="+taskInputDTO.getId();
        for (String item:userOpenId){
          wxTemplateDO.setSendto(item);
          wxTemplateDO.setFirst(first);
          wxTemplateDO.setUrl(url);
          wxTemplateDO.setKeyword1(keyword1);
          wxTemplateDO.setKeyword2(keyword2);
          wxTemplateDO.setSendby("系统");
          wxTemplateDO.setRemarks("");
          wxTemplateDO.setAddtime(TimestampUtils.timestamp());
          wxTemplateDao.insertSelective(wxTemplateDO);
        }
        log.info("userOpenId{}",userOpenId);
    }



    /**
     * 获取任务详情
     * @param id Integer
     * return Object
     * */
    @Override
    public Map<String, Object> getTaskDetail(Integer id) {
        Map<String,Object> list = taskDao.getTaskDetail(id);
        if(list == null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
        }
        String timeFormat = "yyyy-MM";
        String start_time = TimestampUtils.getDateTimeOfTimestamp((Integer) list.get("start_time"),timeFormat);
        String end_time = TimestampUtils.getDateTimeOfTimestamp((Integer) list.get("end_time"),timeFormat);
        list.put("start_time",start_time);
        list.put("end_time",end_time);
        return list;
    }


    /**
     * 编辑任务
     * @param taskDO TaskDO
     * return boolean
     * */
    @Override
    @Transactional
    public void editTask(TaskDO taskDO) {
        Integer nowTime = TimestampUtils.timestamp();
        Integer exist = taskDao.checkTaskTitle(taskDO.getTitle(),taskDO.getClassId(),nowTime,taskDO.getId());

        //还没过期的同一类型的不能同名
      if(taskDO.getId() != null){
          //编辑
          taskDO.setAddtime(TimestampUtils.timestamp());
          taskDao.updateByPrimaryKeySelective(taskDO);
      }else{
          taskDO.setAddtime(TimestampUtils.timestamp());
          taskDao.insertSelective(taskDO);
      }
    }


    /**
     * 增加浏览量
     * @param openId String id Integer
     * return boolean
     * */
    @Override
    @Transactional
    public void addReadTask(String openId, Integer id) {
        //1.查询当前任务是否存在
        //2.查询当前任务是否已经过期或者不存在
        //3.查询当前任务是否已经阅读过
        //4.写入记录，增加本身的taskid和原来的任务的阅读量
        Integer nowTime = TimestampUtils.timestamp();
        UserTaskDO userTaskDO = userTaskDao.selectByPrimaryKey(id);
        if(userTaskDO != null){
            TaskDO taskDO = taskDao.selectByPrimaryKey(userTaskDO.getTaskId());
            if(taskDO != null){
                if(taskDO.getEndTime() > nowTime){
                    //查询是否存在记录
                    Integer exist = taskReadDao.selectExistReadByOpenId(openId,userTaskDO.getTaskId(),userTaskDO.getUid());
                    if(exist == null){
                        //插入记录
                        TaskReadDO taskReadDO = new TaskReadDO();
                        taskReadDO.setOpenid(openId);
                        taskReadDO.setTaskId(userTaskDO.getTaskId());
                        taskReadDO.setUid(userTaskDO.getUid());
                        taskReadDO.setAddtime(TimestampUtils.timestamp());
                        taskReadDao.insertSelective(taskReadDO);
                        //添加阅读量
                        UserTaskDO userTask = new UserTaskDO();
                        userTask.setReaded(userTaskDO.getReaded()+1);
                        userTask.setId(id);
                        userTaskDao.updateByPrimaryKeySelective(userTask);
                        //添加原来的任务的阅读量
                        TaskDO task = new TaskDO();
                        task.setId(userTaskDO.getTaskId());
                        task.setReaded(taskDO.getReaded()+1);
                        taskDao.updateByPrimaryKeySelective(task);
                    }
                }

            }
        }

    }

    /**
    * 获取员工下面的任务详情
    * */
    @Override
    public Map<String, Object> getTaskInfo(Integer id) {
        UserTaskDO userTask = userTaskDao.selectByPrimaryKey(id);
        if(userTask  == null){
            throw BusinessException.of(ErrorMessageEnum.TASK_NOT_FOUND);
        }
        TaskDO taskDO = taskDao.selectByPrimaryKey(userTask.getTaskId());
        Integer nowTime = TimestampUtils.timestamp();
        if(taskDO.getEndTime() < nowTime){
            throw BusinessException.of(ErrorMessageEnum.TASK_IS_OVERTIME);
        }
        Map<String,Object> detail = userTaskDao.getUserTaskDetail(id);
        String timeFormat = "yyyy-MM-dd hh:mm:ss";
        String start_time = TimestampUtils.getDateTimeOfTimestamp((Integer) detail.get("start_time"),timeFormat);
        String end_time = TimestampUtils.getDateTimeOfTimestamp((Integer) detail.get("end_time"),timeFormat);
        String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) detail.get("addtime"),timeFormat);
        detail.put("start_time",start_time);
        detail.put("end_time",end_time);
        detail.put("addtime",addtime);
        return detail;
    }


    /**
     * 获取分享页面
     *
     * */
    @Override
    public ModelAndView getShareView(String url) {
        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
        WxJsapiSignature jsapiSignature;
        try {
            jsapiSignature = wxMpService.createJsapiSignature(url);
            ModelAndView mav = new ModelAndView("show/share");
            mav.addObject("appId",jsapiSignature.getAppId());
            mav.addObject("nonceStr",jsapiSignature.getNonceStr());
            mav.addObject("timestamp",String.valueOf(jsapiSignature.getTimestamp()));
            mav.addObject("signature",jsapiSignature.getSignature());
            mav.addObject("url",jsapiSignature.getUrl());
            return mav;
        }catch (WxErrorException e) {
            e.printStackTrace();
            return null;
        }
    }


}
